/**
 * Created by Freeman on 2016/7/25.
 */

import * as types from '../constants/ActionTypes'

import { CALL_API, Schemas } from '../api'

function fetchUser(login) {
    return {
        [CALL_API]: {
            types: [ types.USER_REQUEST, types.USER_SUCCESS, types.USER_FAILURE ],
            endpoint: `users/${login}`,
            schema: Schemas.USER
        }
    }
}
export function loadUser(login, requiredFields = []) {
    return (dispatch, getState) => {
        const user = getState().entities.users[login]
        if (user && requiredFields.every(key => user.hasOwnProperty(key))) {
            return null
        }

        return dispatch(fetchUser(login))
    }
}


function fetchRepo(fullName) {
    return {
        [CALL_API]: {
            types: [ types.REPO_REQUEST, types.REPO_SUCCESS, types.REPO_FAILURE ],
            endpoint: `repos/${fullName}`,
            schema: Schemas.REPO
        }
    }
}
export function loadRepo(fullName, requiredFields = []) {
    return (dispatch, getState) => {
        const repo = getState().entities.repos[fullName]
        if (repo && requiredFields.every(key => repo.hasOwnProperty(key))) {
            return null
        }

        return dispatch(fetchRepo(fullName))
    }
}

function fetchStarred(login, nextPageUrl) {
    return {
        login,
        [CALL_API]: {
            types: [ types.STARRED_REQUEST, types.STARRED_SUCCESS, types.STARRED_FAILURE ],
            endpoint: nextPageUrl,
            schema: Schemas.REPO_ARRAY
        }
    }
}
export function loadStarred(login, nextPage) {
    return (dispatch, getState) => {
        const {
            nextPageUrl = `users/${login}/starred`,
            pageCount = 0
        } = getState().pagination.starredByUser[login] || {}

        if (pageCount > 0 && !nextPage) {
            return null
        }

        return dispatch(fetchStarred(login, nextPageUrl))
    }
}


function fetchStargazers(fullName, nextPageUrl) {
    return {
        fullName,
        [CALL_API]: {
            types: [ types.STARGAZERS_REQUEST, types.STARGAZERS_SUCCESS, types.STARGAZERS_FAILURE ],
            endpoint: nextPageUrl,
            schema: Schemas.USER_ARRAY
        }
    }
}

// Fetches a page of stargazers for a particular repo.
// Bails out if page is cached and user didn't specifically request next page.
// Relies on Redux Thunk middleware.
export function loadStargazers(fullName, nextPage) {
    return (dispatch, getState) => {
        const {
            nextPageUrl = `repos/${fullName}/stargazers`,
            pageCount = 0
        } = getState().pagination.stargazersByRepo[fullName] || {}

        if (pageCount > 0 && !nextPage) {
            return null
        }

        return dispatch(fetchStargazers(fullName, nextPageUrl))
    }
}

export function resetErrorMessage() {
    return {
        type: types.RESET_ERROR_MESSAGE
    }
}